package pers.ervinse.shoppingmall.gpt.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;

import okhttp3.ResponseBody;
import pers.ervinse.shoppingmall.BaseFragment;
import pers.ervinse.shoppingmall.R;
import pers.ervinse.shoppingmall.api.ApiService;
import pers.ervinse.shoppingmall.api.RetrofitClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ChatFragment extends BaseFragment {

    private static final String TAG = ChatFragment.class.getSimpleName();

    private TextView chatContentTextView;
    private EditText messageInputEditText;
    private Button sendButton;
    private Button newChatButton;
    private ScrollView scrollView;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_community, container, false);

        // 初始化控件
        chatContentTextView = view.findViewById(R.id.tv_chat_content);
        messageInputEditText = view.findViewById(R.id.et_message_input);
        sendButton = view.findViewById(R.id.btn_send);
        newChatButton = view.findViewById(R.id.btn_new_chat);
        scrollView = view.findViewById(R.id.scrollView);

        // 监听发送按钮点击事件
        sendButton.setOnClickListener(v -> {
            String message = messageInputEditText.getText().toString().trim();
            if (!message.isEmpty()) {
                sendMessageToBackend(message);
            } else {
                Toast.makeText(getContext(), "请输入消息", Toast.LENGTH_SHORT).show();
            }
        });

        // 监听新建对话按钮点击事件
        newChatButton.setOnClickListener(v -> {
            // 清空当前聊天内容
            chatContentTextView.setText("");
            messageInputEditText.setText("");
        });

        return view;
    }

    @Override
    public View initView() {
        return null;
    }

    @Override
    public void refreshData() {
        // Not implemented
    }

    @Override
    public void saveData() {
        // Not implemented
    }

    // 发送消息给后端
    private void sendMessageToBackend(String message) {
        ApiService apiService = RetrofitClient.getApiService();

        // 禁用发送按钮，防止重复点击
        sendButton.setEnabled(false);

        // 发起与后端的请求
        Call<ResponseBody> call = apiService.getGPTResponse(message);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                // 请求完成后恢复按钮
                sendButton.setEnabled(true);

                if (response.isSuccessful() && response.body() != null) {
                    try {
                        // 获取纯文本响应内容
                        String responseMessage = response.body().string();
                        // 显示后端返回的消息
                        chatContentTextView.append("\nUser: " + message);
                        chatContentTextView.append("\nAI: " + responseMessage);
                        scrollView.post(() -> scrollView.fullScroll(View.FOCUS_DOWN)); // 滚动到底部显示最新消息
                        messageInputEditText.setText(""); // 清空输入框
                    } catch (IOException e) {
                        e.printStackTrace();
                        Toast.makeText(getContext(), "解析返回内容失败", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(getContext(), "请求失败，请重试！", Toast.LENGTH_SHORT).show();
                    Log.e(TAG, "gpt请求失败,：" + response.code());
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                // 请求失败时恢复按钮并显示错误信息
                sendButton.setEnabled(true);
                Toast.makeText(getContext(), "请求失败，请重试！", Toast.LENGTH_SHORT).show();
                Log.e(TAG, "请求错误：" + t.getMessage());
            }
        });
    }
}
